package com.eagle.service;

import android.app.ActivityManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.TrafficStats;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.eagle.EApplication;
import com.eagle.support.constants.Constants;
import com.eagle.support.helper.CallHelper;
import com.eagle.support.utils.Utils;
import com.eagle.view.activity.MainActivity_;
import com.kinstalk.voip.sdk.EngineSdkCallState;
import com.kinstalk.voip.sdk.EngineSdkVideoPixelFormat;
import com.kinstalk.voip.sdk.logic.sip.aidl.model.CallInfo;

import org.androidannotations.annotations.EService;

import java.util.List;

/**
 * Created by gc on 2016/12/31. 实时网速检测
 */
@EService
public class TrafficService extends Service implements CallHelper.ICallStateListener, CallHelper.IDataResultListener, CallHelper.IMeetingStateListener {

    private long mLastDownloadTotal = 0, mLastUploadTotal = 0;

    private CallHelper mHelper;

    private boolean mSpeedStarted;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        flags = START_STICKY;
        mHelper = CallHelper.getInstance();
        mHelper.registerCallStateListener(this);
        mHelper.registerMeetingStateListener(this);
        if (!mSpeedStarted) {
            mHandler.sendEmptyMessage(0);
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            trafficMonitor();
            mHandler.sendEmptyMessageDelayed(0, 5000);
            mSpeedStarted = true;
        }
    };

    /**
     * 遍历有联网权限的应用程序的流量记录
     */
    private void trafficMonitor() {
        try {
            ApplicationInfo ai = getPackageManager().getApplicationInfo(getApplication().getPackageName(), PackageManager.GET_ACTIVITIES);
            if (ai == null) {
                ai = getPackageManager().getApplicationInfo("com.kinstalk.voip.sdk.service", PackageManager.GET_ACTIVITIES);
            }

            long downloadTotal = TrafficStats.getUidRxBytes(ai.uid);
            long uploadTotal = TrafficStats.getUidTxBytes(ai.uid);

            long downloadSpeed = 0, uploadSpeed = 0;
            if (mLastDownloadTotal > 0) {
                downloadSpeed = (downloadTotal - mLastDownloadTotal) / 5l;
            }

            if (mLastUploadTotal > 0) {
                uploadSpeed = (uploadTotal - mLastUploadTotal) / 5l;
            }


            if (mLastDownloadTotal > 0 && mLastUploadTotal > 0) {
                Intent intent = new Intent(Constants.ACTION_NET_WORK_SPEED);
                intent.putExtra("rx", Utils.formatSize(downloadSpeed));
                intent.putExtra("tx", Utils.formatSize(uploadSpeed));
                sendBroadcast(intent);
            }

            mLastDownloadTotal = downloadTotal;
            mLastUploadTotal = uploadTotal;
            Log.e("cim", "trafficMonitor: " + Utils.formatSize(downloadSpeed) + "-" + Utils.formatSize(uploadSpeed));
        } catch (PackageManager.NameNotFoundException e) {
            Log.e("cim", "TrafficService Ex:" + e.getMessage().toString());
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeMessages(0);
            mHandler = null;
        }
    }

    @Override
    public void onCallStateHandler(CallInfo call, int state) {
        switch (EngineSdkCallState.swigToEnum(state)) {
            case ES_STATE_ON_CALL_INCOMMING_CALL:
                String uid = EApplication.getSharedPreferences().getString(Constants.LOGIN_UID, "");
                if (EngineSdkCallState.swigToEnum(state) == EngineSdkCallState.ES_STATE_ON_CALL_INCOMMING_CALL && !TextUtils.isEmpty(uid)) {
                    MainActivity_.intent(getBaseContext()).
                            flags(Intent.FLAG_ACTIVITY_NEW_TASK).
                            extra(Constants.CALL_TYPE, Constants.CALL_TYPE_INCOMING).
                            extra(Constants.CALL_UID, call.getCallConfiguration().getRemoteAccountId()).
                            start();
                }
                break;
        }
    }


    @Override
    public void onMessageSendResult(String roomId) {
        Log.e("cim", "TrafficService onMessageSendResult: " + roomId);
    }

    @Override
    public void onPushAddCid(String cid) {
        Log.e("cim", "TrafficService onPushAddCid: " + cid);
    }

    @Override
    public void onPushByeCid(String cid) {
        Log.e("cim", "TrafficService onPushByeCid: " + cid);
    }

    @Override
    public void onMainVideoDataInCall(long callToken, long pointer, int width, int height, char rotation, EngineSdkVideoPixelFormat format, long channelId) {

    }

    @Override
    public void onGotInviteResult(String roomId, String sender) {
        String uid = EApplication.getSharedPreferences().getString(Constants.LOGIN_UID, "");
        if (!TextUtils.isEmpty(sender) && !TextUtils.isEmpty(uid) && isApplicationBroughtToBackground(getApplicationContext())) {
            MainActivity_.intent(getBaseContext()).
                    flags(Intent.FLAG_ACTIVITY_NEW_TASK).
                    extra(Constants.CALL_TYPE, Constants.CALL_TYPE_MEETING_INVITE).
                    extra(Constants.ROOM_ID, roomId).
                    extra(Constants.MEETING_SENDER, sender).
                    start();
        }
    }

    @Override
    public void onGotMeetingRoomResult(String roomId) {

    }

    /**
     * 判断当前应用程序处于前台还是后台
     */
    public static boolean isApplicationBroughtToBackground(final Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }
}
